<template>
  <div class="setting-container">
    <div class="app-container">
      <el-card v-loading="loading">
        <el-tabs v-model="activeName">
          <el-tab-pane label="角色管理" name="first">
            <!-- 按钮 -->
            <el-button size="small" type="primary" @click="isShow = true">+ 新增角色</el-button>

            <!-- 表格 -->
            <el-table :data="list">
              <el-table-column label="序号" type="index" :index="indexFn" />
              <!-- <el-table-column label="序号" width="120">
                <template #default="{ $index }">{{ $index+1+(page-1)*pagesize }}</template>
              </el-table-column> -->

              <!-- <el-table-column label="角色名称" prop="name" /> -->
              <el-table-column label="角色名称" width="240">
                <template #default="{row}">
                  {{ row.name }}
                </template>
              </el-table-column>

              <el-table-column label="描述" prop="description" />

              <el-table-column label="操作">
                <!-- 组件内部<slot name="default" :row="xx" :column="xx" :$index="xx" /> -->
                <template #default="{ row }">
                  <el-button size="small" type="success" @click="assignPerm(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="edit(row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="del(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <el-pagination
              style="margin-top: 20px"
              :current-page="page"
              :page-sizes="[1,2,3,4,5]"
              :page-size="pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-tab-pane>
          <el-tab-pane label="公司信息" name="second">
            <!-- 警告信息 -->
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="companyForm.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="companyForm.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="companyForm.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="companyForm.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>

      <!-- 添加的弹层 / 编辑 -->
      <el-dialog :title="title" :visible="isShow" @close="closeDialog">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="form.description" placeholder="请输入角色描述" />
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button size="small" @click="closeDialog">取消</el-button>
          <el-button size="small" type="primary" @click="submit">确认</el-button>
        </template>
      </el-dialog>

      <!-- 分配角色的弹窗 -->
      <!-- 分配权限的弹层 -->
      <el-dialog title="分配权限" :visible="showAssignDialog" @close="closeAssignDialog">
        <!-- 内容部分 -->
        <!--
          show-checkbox 节点是否可以被选择  布尔值
          check-strictly  控制父子不互相关联   默认是互相影响互相关联   布尔值
          node-key="id"   配合获取选中项  设置的是将来收集的字段  因为将来我需要的就是选中的权限的id
         -->
        <el-tree
          ref="tree"
          :data="permissionList"
          :props="{ label: 'name' }"
          default-expand-all
          show-checkbox
          check-strictly
          node-key="id"
        />
        <template #footer>
          <el-button @click="closeAssignDialog">取消</el-button>
          <el-button type="primary" @click="assign">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { reqAddRole, reqDelRole, reqGetRoleDetail, reqGetRoleList, reqUpdateRole, reqAssignPerm } from '@/api/setting'
import { reqGetCompanyById } from '@/api/company'
import { reqGetPermissionList } from '@/api/permission'
import { mapState } from 'vuex'
import { transListToTreeData } from '@/utils'
export default {
  name: 'Setting',
  data() {
    return {
      activeName: 'first',
      list: [],
      page: 1,
      pagesize: 3,
      total: 0,
      loading: false,
      isShow: false,
      form: {
        name: '',
        description: '' // 字段写错了
      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: ['blur', 'change'] }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: ['blur', 'change'] }
        ]
      },
      companyForm: {
        name: '',
        companyAddress: '',
        mailbox: '',
        remarks: ''
      },
      showAssignDialog: false,
      permissionList: [],
      roleId: '' // 即将被分配权限的角色id
    }
  },
  computed: {
    ...mapState('user', ['userInfo']),
    title() {
      return this.form.id ? '编辑角色' : '添加角色'
    }
  },
  created() {
    this.getRoleList()
    this.getCompanyInfo()
  },
  methods: {
    indexFn(index) {
      // index 下标
      return index + 1 + this.pagesize * (this.page - 1)
    },
    async getRoleList() {
      this.loading = true
      const { data: { rows, total }} = await reqGetRoleList(this.page, this.pagesize)
      // console.log(res)
      this.list = rows
      this.total = total
      this.loading = false
    },
    del(id) {
      // console.log(id)
      this.$confirm('你确认要删除该角色么?', '温馨提示', {
        cancelButtonText: '否',
        confirmButtonText: '是',
        type: 'warning'
      }).then(async() => {
        // console.log('确定')
        await reqDelRole(id)
        // this.$message.success('删除成功')
        this.$message({
          type: 'success',
          message: '删除成功'
        })
        // 如果删除的是本页最后一条数据 去上一页
        if (this.list.length === 1 && this.page > 1) {
          this.page--
        }

        this.getRoleList()
        // this.$emit('refresh')
      }).catch(() => {
        // console.log('取消')
      })
    },
    handleSizeChange(val) {
      // 用户选择的每页条数
      // console.log(val)
      this.pagesize = val
      // 细节: 我们一共有100条数据, 现在是每页1条 可以有100页, 可以在第80页; 切换每页100条, 只有1页,
      // 每页条数变化后, 重置页码
      this.page = 1
      this.getRoleList()
    },
    handleCurrentChange(val) {
      // 用户选择的页码
      // console.log(val)
      this.page = val
      this.getRoleList()
    },
    closeDialog() {
      this.isShow = false
      this.$refs.form.resetFields()
      // 注意!!! 手动重置表单之外的数据
      this.form = {
        name: '',
        description: ''
      }
    },
    // 查 删 增 改
    async submit() {
      try {
        await this.$refs.form.validate()
        if (this.form.id) {
          // 编辑
          await reqUpdateRole(this.form)
          this.$message.success('编辑角色成功')
        } else {
          // 添加
          await reqAddRole(this.form)
          this.$message.success('新增角色成功')
        }
        this.closeDialog()
        this.getRoleList()
      } catch (e) {
        console.log(e)
      }
    },
    async edit(id) {
      // 获取单个角色详情
      const { data } = await reqGetRoleDetail(id)
      this.form = data // 利用form已经双向数据绑定 进行回显
      this.isShow = true // 显示弹窗
    },
    async getCompanyInfo() {
      const { data } = await reqGetCompanyById(this.userInfo.companyId)
      this.companyForm = data
    },
    async assignPerm(id) {
      // console.log(id) // 将来需要知道给哪个角色 分配权限
      this.roleId = id
      this.showAssignDialog = true // 打开弹窗

      // 发请求 获取权限列表数据 用于展示
      const { data } = await reqGetPermissionList() // 列表数据
      const res = transListToTreeData(data, '0') // 树形数据
      // console.log(res)
      this.permissionList = res // 存一下

      // 请求 角色详情
      const res2 = await reqGetRoleDetail(id)
      // res2.data.permIds
      this.$refs.tree.setCheckedKeys(res2.data.permIds)
    },
    closeAssignDialog() {
      this.showAssignDialog = false

      this.$refs.tree.setCheckedKeys([]) // 清空选中项
    },
    async assign() {
      // 细节: 需要搭配一个额外的属性
      // const res = this.$refs.tree.getCheckedKeys() // 获取选中项
      // console.log(res)
      // this.$refs.tree.setCheckedKeys([]) // 什么都不选中
      // this.$refs.tree.setCheckedKeys(['604f7e07f900be1850edb153', '604f7e66f900be1850edb157'])
      // -------------------------------------------------------

      // 获取选中权限们 发请求分配权限
      const checkedPermissionList = this.$refs.tree.getCheckedKeys()
      // console.log(checkedPermissionList)
      await reqAssignPerm(this.roleId, checkedPermissionList)
      this.$message.success('分配权限成功')
      this.closeAssignDialog()
    }
  }
}
</script>

<style lang='scss' scoped>
// .el-pagination {
//   margin-top: 20px;
// }

</style>
